import Vue from 'vue'
import VueRouter from 'vue-router'

// 1.导入页面
import Reg from '@/views/reg'
import Login from '@/views/login'

// 导入vuex实例
import store from '@/store'
// 导入父页面
import Layout from '@/views/layout'

// 导入子页面
import Home from '@/views/home'
import UserInfo from '@/views/user/userInfo.vue'
import UserPhoto from '@/views/user/userPhoto.vue'
import UserPwd from '@/views/user/userPwd.vue'
import Cate from '@/views/article/cate.vue'
import List from '@/views/article/list.vue'

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

// 配置路由跳转规则
const routes = [
  // 注册页面
  {
    path: '/reg',
    component: Reg
  },
  // 登录页面
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home

      },
      {
        path: '/user-info',
        component: UserInfo
      },
      {
        path: '/user-avatar',
        component: UserPhoto
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: '/art-cate',
        component: Cate
      },
      {
        path: '/art-list',
        component: List
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const vips = ['/login', '/reg']
  if (vips.includes(to.path)) {
    next()
  } else {
    if (store.state.user.token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
